package linces

import (
	"db2s/global"
	"db2s/outPut"
	"encoding/json"
	"fmt"
	"os"
	"reflect"
)

type MachineAuth struct {
	MachineCode string `json:"machineCode"`
	AuthCode    string `json:"authCode"`
}

func readAuth() (p string) {
	ff := outPut.FileOut("text", map[string]any{"fileName": File, "rowsS": "\n"})
	m := ff.Read1()
	for {
		select {
		case c, ok := <-m.(chan any):
			if !ok {
				return
			}
			switch fmt.Sprintf("%v", reflect.TypeOf(c)) {
			case "*string":
				p = *c.(*string)
			}
		}
	}
}
func authCodeRegister() string {
	machineCode := GetMachineCode()
	return GenerateAuthCode(machineCode, AesKey)
}

// 生成授权码
func licenseCheck(AuthCode string) bool {
	var (
		ce       string
		authFail string
		authCode string
		r        = MachineAuth{}
	)
	//判断ca文件是否存在
	caS := global.FileExists(File)
	//获取机器码
	machineCode := GetMachineCode()
	authFail = fmt.Sprintf("report: The current machine code is %v, please contact the administrator for authorization!!!", machineCode)
	//判断是否存在授权文件，并且未输入授权密码
	if !caS && len(AuthCode) == 0 {
		fmt.Println(authFail)
		return false
	}
	//ca认证文件不存在才会使用输入的授权码
	if !caS && len(AuthCode) > 0 {
		authCode = AuthCode
	}
	//启动时未指定授权密码
	if caS {
		p := readAuth()
		if err := json.Unmarshal([]byte(p), &r); err != nil {
			fmt.Println(fmt.Sprintf("report: Failed to read authorization file %v, please authorize again.", File))
			return false
		}
		authCode = r.AuthCode
	}
	//开启授权码解密
	if len(authCode) > 0 {
		ce = GetDecryCode(authCode, AesKey)
	}
	if machineCode == ce {
		r.MachineCode = machineCode
		r.AuthCode = authCode
		if !global.FileExists(File) {
			if q, err := json.Marshal(r); err != nil {
				fmt.Println(fmt.Sprintf("report: Failed to parse authorization file %v. please authorize again.", File))
				return false
			} else {
				var f *os.File
				if f, err = os.OpenFile(File, os.O_TRUNC|os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0664); err != nil {
					fmt.Println(fmt.Sprintf("report: Failed to create authorization file %v, please authorize again.", File))
					return false
				}
				WriteTextI := outPut.FileOut("text", map[string]any{"fileN": f, "logSeq": int64(1), "bufSize": 1024 * 1024 * 4, "rowsS": "\n"})
				WriteTextI.AppendWrite("", string(q))
				if err = WriteTextI.Close(); err != nil {
					fmt.Println(fmt.Sprintf("report: Failed to close authorization file %v, please authorize again.", File))
					return false
				}
			}
			fmt.Println(fmt.Sprintf("report: Authorization file %v updated successfully. Please feel free to use it.", File))
			return false
		}
		return true
	}
	fmt.Println(authFail)
	return false
}
func LinesRegister(CertificationFree bool, AuthCode string) bool {
	var code string
	if CertificationFree {
		code = authCodeRegister()
	} else {
		code = AuthCode
	}
	//lines认证
	return licenseCheck(code)
}
